package com.example.servlet;

import com.example.dao.UserDao;
import com.example.domain.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

@WebServlet("/AdminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("adminName");
        String password = request.getParameter("adminPassword");
        String code = request.getParameter("verification");
        HttpSession session = request.getSession();
        String verificationCode = (String)session.getAttribute("verificationCode");
        if(!verificationCode.equals(code)){
            response.getWriter().write("codeError");
            return;
//            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
        UserDao userDao = new UserDao();
        User user = userDao.getUserByUsernameAndPassword(username, password);
        if(user == null){
            if (userDao.checkUsername(username)){
                response.getWriter().write("passwordError");
                return;
//                request.getRequestDispatcher("login.jsp").forward(request,response);
            }else{
                response.getWriter().write("usernameError");
                return;
//                request.getRequestDispatcher("login.jsp").forward(request,response);
            }
        }
        if(user.isIsAdmin()){
            response.getWriter().write("登录成功！");
            request.getSession().removeAttribute("verificationCode");
            request.getSession().setAttribute("user",user);
        }else{
            response.getWriter().write("no");
//            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }
    public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
        doGet(request,response);
    }
}
